/*
 * jquery.juice.tooltip.js
 *
 * Juice Library Tooltip v0.1.0
 * Date: 2009-05-04
 * Requires: jQuery v1.3 or later
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Copyright 2009 Steve Whiteley (http://jui.ce.it)
 */

(function($) {
	$.fn.tooltip = function(callerSettings) {
		var settings = $.extend(true, {}, $.fn.tooltip.settings, callerSettings);
		return this.each(function() {
			var n = $(this), t;
			var setup = function() {
				t = $('<div />')
					.css({
						position: 'absolute',
						opacity: settings.opacity,
						zIndex: 1000
					})
					.addClass(settings.className)
					.hide()
					.appendTo('body');
				n.mouseover(show)
					.mouseout(hide)
					.mousemove(position);
				if (!settings.position) {
					settings.left = settings.left || 10;
					settings.top = settings.top || 10;
				}
			};
			var show = function(e) {
				var text;
				if (text = n.attr('alt') || n.attr('title')) {
					n.data('tooltip', {
						alt: n.attr('alt'),
						title: n.attr('title')
					})
					.removeAttr('title')
					.removeAttr('alt');
					t.html(text).stop(true, true).fadeIn(settings.fade);
					position(e);
				}
			};
			var position = function(e) {
				var top, left, offset = n.offset();
				switch (settings.position) {
					case 'tl':
						top = offset.top - t.outerHeight();
						left = offset.left - t.outerWidth(); 
					break;
					case 'tm':
						top = offset.top - t.outerHeight();
						left = offset.left - ((t.outerWidth() - n.outerWidth()) / 2); 
					break;
					case 'tr':
						top = offset.top - t.outerHeight();
						left = offset.left + n.outerWidth();
					break;
					case 'ml':
						top = offset.top - (n.outerHeight() / 2);
						left = offset.left - t.outerWidth()
					break;
					case 'mr':
						top = offset.top - (n.outerHeight() / 2);
						left = offset.left + n.outerWidth();
					break;
					case 'bl':
						top = offset.top + n.outerHeight();
						left = offset.left - t.outerWidth();
					break;
					case 'bm':
						top = offset.top + n.outerHeight();
						left = offset.left - ((t.outerWidth() - n.outerWidth()) / 2); 
					break;
					case 'br':
						top = offset.top + n.outerHeight();
						left = offset.left + n.outerWidth();
					break;
					default:
						top = e.pageY; 
						left = e.pageX;
					break;
				}
				t.css({ top: top + settings.top, left: left + settings.left});
			};
			var hide = function(e) {
				n.attr({
					alt: n.data('tooltip').alt,
					title: n.data('tooltip').title
				});
				t.stop(true, true).fadeOut(settings.fade);
			};
			setup();
		});
	};
	$.fn.tooltip.settings = {
		className: 'juice-tooltip',
		fade: 'normal',
		left: 0,
		opacity: 1,
		position: false,
		top: 0
	};
})(jQuery);
